/*
 * Copyright (C) 2020 Graylog, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the Server Side Public License, version 1,
 * as published by MongoDB, Inc.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * Server Side Public License for more details.
 *
 * You should have received a copy of the Server Side Public License
 * along with this program. If not, see
 * <http://www.mongodb.com/licensing/server-side-public-license>.
 */
package org.graylog2.lookup.adapters.dsvhttp;

import mockwebserver3.MockResponse;
import mockwebserver3.MockWebServer;
import mockwebserver3.RecordedRequest;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class HTTPFileRetrieverTest {
    private MockWebServer server;

    @BeforeEach
    public void setUp() throws Exception {
        server = new MockWebServer();
    }

    @Test
    public void successfulRetrieve() throws Exception {
        this.server.enqueue(new MockResponse(200, Headers.of(), "foobar"));
        server.start();

        final HTTPFileRetriever httpFileRetriever = new HTTPFileRetriever(new OkHttpClient());

        final Optional<String> body = httpFileRetriever.fetchFileIfNotModified(server.url("/").toString());
        final RecordedRequest request = server.takeRequest();

        assertThat(request).isNotNull();
        assertThat(request.getUrl().encodedPath()).isEqualTo("/");

        assertThat(body).isNotNull()
                .isPresent()
                .contains("foobar");
    }

    @Test
    public void doNotRetrieveIfNotModified() throws Exception {
        this.server.enqueue(new MockResponse(
                200,
                Headers.of("Last-Modified", "Fri, 18 Aug 2017 15:02:41 GMT"),
                "foobar"));
        this.server.enqueue(new MockResponse(
                304,
                Headers.of("Last-Modified", "Fri, 18 Aug 2017 15:02:41 GMT"),
                ""));
        server.start();

        final HTTPFileRetriever httpFileRetriever = new HTTPFileRetriever(new OkHttpClient());

        final Optional<String> body = httpFileRetriever.fetchFileIfNotModified(server.url("/").toString());
        final RecordedRequest request = server.takeRequest();

        assertThat(request).isNotNull();
        assertThat(request.getUrl().encodedPath()).isEqualTo("/");

        assertThat(body).isNotNull()
                .isPresent()
                .contains("foobar");

        final Optional<String> secondBody = httpFileRetriever.fetchFileIfNotModified(server.url("/").toString());
        final RecordedRequest secondRequest = server.takeRequest();

        assertThat(secondRequest).isNotNull();
        assertThat(secondRequest.getUrl().encodedPath()).isEqualTo("/");
        assertThat(secondRequest.getHeaders().get("If-Modified-Since")).isEqualTo("Fri, 18 Aug 2017 15:02:41 GMT");

        assertThat(secondBody).isNotNull()
                .isEmpty();
    }

    @Test
    public void fetchFileDoesNotSendIfModifiedSinceHeader() throws Exception {
        final MockResponse response = new MockResponse(200,
                Headers.of("Last-Modified", "Fri, 18 Aug 2017 15:02:41 GMT"),
                "foobar");
        this.server.enqueue(response);
        this.server.enqueue(response);
        server.start();

        final HTTPFileRetriever httpFileRetriever = new HTTPFileRetriever(new OkHttpClient());

        assertThat(httpFileRetriever.fetchFileIfNotModified(server.url("/").toString()))
                .isNotNull()
                .isPresent()
                .contains("foobar");
        assertThat(server.takeRequest()
                .getHeaders().get("If-Modified-Since")).isNull();

        assertThat(httpFileRetriever.fetchFile(server.url("/").toString()))
                .isNotNull()
                .isPresent()
                .contains("foobar");
        assertThat(server.takeRequest()
                .getHeaders().get("If-Modified-Since")).isNull();
    }

    @Test
    public void unsuccessfulRetrieve() throws Exception {
        this.server.enqueue(new MockResponse(
                500,
                Headers.of(),
                "Error!"));
        server.start();

        final HTTPFileRetriever httpFileRetriever = new HTTPFileRetriever(new OkHttpClient());

        Throwable exception = assertThrows(IOException.class, () -> {

            final Optional<String> ignored = httpFileRetriever.fetchFileIfNotModified(server.url("/").toString());
        });
        org.hamcrest.MatcherAssert.assertThat(exception.getMessage(), containsString("Request failed: Server Error"));
    }

    @AfterEach
    public void shutDown() throws IOException {
        if (server != null) {
            server.close();
        }
    }
}
